import os
import os.path
import sys
from flask import Flask
from flask_sqlalchemy import SQLAlchemy  # 导入数据库 ORM 模块
from flask_cors import CORS  # 导入跨域配置模块

# 修复pyinstaller打包后报错: No module named 'sqlalchemy.sql.default_comparator'
import sqlalchemy.sql.default_comparator

# flask_marshmallow 序列化和反序列化模块，
# 用于将复杂的orm模型对象与python原生数据类型之间相互转换
from flask_marshmallow import Marshmallow

# flask_restful 快速构建 REST APIs 的Flask 扩展
# http://www.pythondoc.com/Flask-RESTful/
from flask_restful import Api
import toml

config = toml.load("./server_config.toml")

app = Flask(__name__)  # 创建Flask实例

# 跨域允许
CORS(app, resources={r"/*": {"origins": "*"}})

# 配置数据库连接
# root_path = os.path.dirname(app.root_path)
# 打包成exe后root_path无效, 改用下面的方法
root_path = os.path.dirname(os.path.realpath(sys.argv[0]))
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///" + os.path.join(
    root_path, config["sqlite"]["dbname"]
)

# 关闭数据库对象修改的跟踪
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False

db = SQLAlchemy(app)  # 初始化扩展 SQLAlchemy， 传入程序实例 app
ma = Marshmallow(app)  # 初始化扩展 Marshmallow， 传入程序实例 app
api = Api(app)  # 初始化扩展 Api， 传入程序实例 app


from sensorapp import views, models, command

# 修复pyinstaller打包后运行提示错误: no such table xxx
# https://stackoverflow.com/questions/59491313/flask-sql-no-such-table
db.create_all()

from sensorapp.views import SensorUploadApi, SensorAverageApi  # 导入资源类

api.add_resource(
    SensorUploadApi, "/api/monitor/upload", endpoint="monitor_upload"
)  # 添加资源及访问路径
# api.add_resource(SensorAverageApi, "/api/monitor/average/<float:start>")  # 添加资源及访问路径
api.add_resource(
    SensorAverageApi, "/api/monitor/average", endpoint="monitor_average"
)  # 添加资源及访问路径
